package com.wugh.fast.demo.aop;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.wugh.fast.demo.anno.SpelAnno;
import com.wugh.fast.kernel.core.util.SpelUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class SpelAnnoAspect {

    @Around(value = "@annotation(com.wugh.fast.demo.anno.SpelAnno)")
    public void execute(ProceedingJoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        SpelAnno spelAnno = AnnotationUtils.findAnnotation(method, SpelAnno.class);
        SpelExpressionParser parser = SpelUtils.getExpressionParser();
        EvaluationContext context = SpelUtils.createEvaluationContext(joinPoint);
        Object value = parser.parseExpression(spelAnno.value()).getValue(context);
        log.debug("表达式:{},执行结果:{}", spelAnno.value(), value);
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            ExceptionUtil.wrapAndThrow(throwable);
        }
    }
}
